package cn.itcast.bos.web.action;

import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ExceptionMapping;
import org.apache.struts2.convention.annotation.ExceptionMappings;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.service.base.CourierService;


@ExceptionMappings({
		@ExceptionMapping(exception = "org.apache.shiro.authz.UnauthorizedException", result = "unauthorized") })
@Results({@Result(name="unauthorized",location="/unauthorized.html")})

@Namespace("/")
@ParentPackage("json-default")
@Action
@Scope("prototype")
public class CourierAction extends ActionSupport implements ModelDriven<Courier> {

	private Courier courier = new Courier();

	@Override
	public Courier getModel() {
		return courier;
	}

	@Autowired
	private CourierService courierService;

	// 保存操作
	@Action(value = "courierAction", results = {
			@Result(name = "success", location = "./pages/base/courier.html", type = "redirect") })
	@RequiresPermissions("courier_add")
	public String save() {
		courierService.save(courier);
		return SUCCESS;
	}

	private int page;
	private int rows;

	// 分页查询
	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	@Action(value = "courierPageAction", results = { @Result(name = "success", type = "json") })
	public String findByPage() {
		Pageable pageable = new PageRequest(page - 1, rows);

		Specification<Courier> specification = new Specification<Courier>() {
			@Override
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				// 判断是否为空
				if (StringUtils.isNotBlank(courier.getCourierNum())) {
					Predicate p1 = cb.equal(root.get("courierNum").as(String.class), courier.getCourierNum());
					list.add(p1);
				}
				if (StringUtils.isNotBlank(courier.getCompany())) {
					Predicate p2 = cb.like(root.get("company").as(String.class), "%" + courier.getCompany() + "%");
					list.add(p2);
				}
				if (StringUtils.isNotBlank(courier.getType())) {
					Predicate p3 = cb.equal(root.get("type").as(String.class), courier.getType());
					list.add(p3);
				}
				Join<Object, Object> standardRoot = root.join("standard", JoinType.INNER);
				if (courier.getStandard() != null && StringUtils.isNotBlank(courier.getStandard().getName())) {
					Predicate p4 = cb.like(standardRoot.get("name").as(String.class),
							"%" + courier.getStandard().getName() + "%");
					list.add(p4);
				}
				return cb.and(list.toArray(new Predicate[0]));
			}
		};

		Page<Courier> couriers = courierService.findByPage(specification, pageable);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", couriers.getTotalElements());
		map.put("rows", couriers.getContent());
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}

	// 作废
	private String ids;

	public void setIds(String ids) {
		this.ids = ids;
	}

	@Action(value = "deleteAction", results = {
			@Result(name = "success", location = "./pages/base/courier.html", type = "redirect") })
	public String updateDeltag() {
		String[] idarray = ids.split(",");
		courierService.updateDeltag(idarray);
		return SUCCESS;
	}

	// 定区获得所有快递员
	@Action(value = "courierFindAll", results = { @Result(name = "success", type = "json") })
	public String findAll() {
		List<Courier> couriers = courierService.findAll();

		ActionContext.getContext().getValueStack().push(couriers);
		return SUCCESS;
	}

	@Action(value = "findCourierAll", results = { @Result(name = "success", type = "json") })
	public String findNoAssociation() {
		List<Courier> couriers = courierService.findNoAssociation();
		ActionContext.getContext().getValueStack().push(couriers);
		return SUCCESS;
	}

}
